<template>
  <main>

    <div v-if="hasResource" class="resource-detail-container">
      <div class="resource-detail-card">
        <!-- 收藏按钮 -->
        <div v-if="isLogin" class="resource-collect-section">
          <div v-if="isCollection">
            <h2 class="resourceCollectHint">已经在收藏夹中</h2>
            <button @click="clsCollectResource(viewResource.rId)" class="resourceBtn">
              取消收藏此资源
            </button>
          </div>
          <div v-else>
            <button @click="collectResource(viewResource.rId)" class="resourceBtn">
              收藏此资源
            </button>
          </div>
          <button @click="jump('src/page/home/index.html')" class="backHomeBtn">返回首页</button>
        </div>

        <!-- 资源信息 -->
        <h2 class="resourceTitle">{{ viewResource.rName }}</h2>
        <h3 class="resourceManufacturer">
          资源发行商/会社/作者信息: {{ viewResource.rManufacturer }}
        </h3>
        <h5 class="resourceType">资源类别: {{ viewResource.rType }}</h5>

        <!-- 标签 -->
        <div class="resourceTagContainer">
        <span v-for="tag in viewResource.tags" :key="tag.tagId" class="resourceTag">
          {{ tag.tagName }}
        </span>
        </div>

        <!-- 预览图 -->
        <div class="resourcePreviewContainer">
          <ul>
            <li
                v-for="resourcePreview in viewResource.rPicture"
                :key="resourcePreview"
                class="resourcePreviewItem"
            >
              <img
                  :src="`${globalConst.staticResourceUrl}img/${resourcePreview}`"
                  alt="预览图加载失败!"
              />
            </li>
            <li
                v-if="!viewResource.rPicture || viewResource.rPicture.length <= 0"
                class="resourceNoPreviewItem"
            >
              <h2 class="resourceNoPreviewHint">
                该资源没有设置任何的预览图，如需查看请自行搜索
              </h2>
            </li>
          </ul>
        </div>

        <!-- 简介 -->
        <div class="resourceIntroductionContainer">
          <h6 class="resourceIntroductionTitle">简介:</h6>
          <p class="resourceIntroduction">{{ viewResource.rIntroduction }}</p>
        </div>

        <!-- 链接区 -->
        <div v-if="isLogin" class="resourceLinkContainer">
          <get-links :Resource="viewResource"/>
        </div>

        <!-- 评论区 -->
        <div class="resourceCommentSection" v-show="showComment">
          <h3 class="resourceCommentTitle">评论区</h3>
          <comment-item
              v-for="c in comment"
              :key="c.originalComment.commentId"
              :commentList="c"
              :hasComment="hasComment"
          />

          <div v-if="isLogin" class="comment-input">
            <p>当前状态:{{ oldComment }}</p>
            <textarea
                rows="5"
                cols="60"
                v-model="newComment"
                id="newCommentInput"
                :placeholder="commentPlaceholder"
                class="resourceCommentTextarea"
            ></textarea>
            <button @click="submitComment" class="resourceBtn">发表/回复评论</button>
            <button @click="clsComment" class="resourceBtn">重置评论框和状态</button>
          </div>
        </div>

        <!-- 评论区展开/收起 -->
        <div class="resourceCommentControl">
          <button @click="showComment = !showComment" class="resourceBtn">
            {{ showComment ? '收起评论区' : '展开评论区' }}
          </button>
        </div>
      </div>
    </div>

    <div v-else class="resourceNoDataContainer">
      <h2 class="resourceNoDataHint">
        当前请求的资源不存在，可能被下架或不存在，请换一个试试。
      </h2>
    </div>
  </main>
  <bottom/>
</template>

<script setup lang="ts">
import {
  addUserCollectionList,
  delUserCollection,
  getResources,
  getUser,
  getUserCollectionList,
  getUserToken
} from '@stores/localStorage.ts'
import {Resources} from '@models/Resources.ts'
import axiosInstance from '@utils/axiosInstance.ts'
import ResponseResult from '@models/ReturnResult.ts'
import {onMounted, onUnmounted, ref, watch} from 'vue'
import CommentItem from '@components/comment-item.vue'
import emitter from '@utils/emitter.ts'
import {isNull} from "@utils/stringUtil.ts";
import {globalConst} from "@constants/globalConst.ts";
import Comment from "@models/Comment.ts";
import {CommentWithUser} from "@models/CommentWithUser.ts";
import GetLinks from "@components/get-links.vue";
import Bottom from "@components/bottom.vue";
import {jump} from "@utils/router.js";

const oldComment = ref('直接评论')
const users = getUser()
const userToken = getUserToken()
const showComment = ref(false)
const isLogin = ref(users.hasUserMsg() && !isNull(userToken)) // 判断是否登录
const newComment = ref('')
const comment = ref<Array<CommentWithUser>>([])
const hasComment = ref(true)
const commentPlaceholder = ref('请输入你的逆天评论') // 输入框提示信息
const replyToCommentId = ref<number | null>(null) // 当前回复的评论ID
const resourceId = ref<number | null>(null)
const isCollection = ref(false)
const params = new URLSearchParams(window.location.search)
console.log("users.hasUserMsg():" + users.hasUserMsg())
console.log("token:" + getUserToken())
let id: number | null;
try {
  id = parseInt(<string>params.get('rId'))
  if (!isNaN(id)) {
    resourceId.value = id
  }
} catch (error) {
  console.log(error)
  resourceId.value = null
}
const hasResource = ref<boolean>(resourceId.value !== null)
const viewResource = ref(new Resources())
if (isLogin.value) {//检查当前资源是否在收藏列表里
  const l = await getUserCollectionList()
  if (resourceId.value !== null)
    isCollection.value = l.includes(resourceId.value)
}
if (hasResource.value && resourceId.value !== null) {
  let l = await getResources(resourceId.value)
  if (l) {
    viewResource.value = l
    hasResource.value = true
    document.title = viewResource.value.rName
  } else {
    hasResource.value = false
  }
}
watch(showComment, async (newVal) => {
  if (newVal && comment.value.length === 0 && hasComment.value) {
    try {
      const response = await axiosInstance.get(`${globalConst.baseUrl}Resources/getComments/${resourceId.value}`)
      const responseResult = ResponseResult.fromApiResponse(response.data)

      if (responseResult.isSuccess() && Array.isArray(responseResult.returnResults)) {
        if (responseResult.returnResults.length > 0) {
          comment.value = responseResult.returnResults.map(item =>
              new CommentWithUser(item)
          )
          hasComment.value = true
        } else {
          hasComment.value = false
        }
      } else {
        alert('评论获取失败! 请稍后再试')
      }
    } catch (error) {
      console.error(error)
      alert('评论获取失败! 请稍后再试')
    }
  }
})

function clsComment() {
  newComment.value = '' // 清空输入框
  replyToCommentId.value = null // 重置评论ID
  oldComment.value = '直接评论'
  commentPlaceholder.value = '请输入你的逆天评论' // 重置提示信息
}

async function submitComment() {
  if (newComment.value.trim()) {
    try {
      const response = await axiosInstance.post(`${globalConst.baseUrl}user/behavior/addComments`, {
        comment: newComment.value,
        commentRId: resourceId.value,
        fatherComment: replyToCommentId.value
      })
      if (response.data.operationResult) {
        alert(response.data.msg + ',如果未显示您的评论,请刷新查看您的评论,由于服务器很烂,评论可能会存在3-5分钟的延迟')
        const newCommentMsg = Comment.from({
          comment: newComment.value,
          commentRId: resourceId.value,
          fatherComment: replyToCommentId.value,
          commentId: response.data.commentRId,
          commentUser: getUser().userId,
          commentTime: new Date(),
          sumComment: []
        })
        comment.value.push(new CommentWithUser({
          originalComment: newCommentMsg,
          userName: getUser().userName,
          userHeadPortraitUrl: getUser().userHeadPortraitUrl
        }))
        newComment.value = '' // 清空输入框
        replyToCommentId.value = null // 重置评论ID
        oldComment.value = '直接评论'
        commentPlaceholder.value = '请输入你的逆天评论' // 重置提示信息
      } else {
        alert('评论/回复发布失败, 因为:' + response.data.msg)
      }
    } catch (error) {
      console.error(error)
    }
  } else {
    alert('评论/回复发布失败, 因为评论内容不可为空!')
  }
}

const handleReply = (c: Array<string | number>) => {
  replyToComment(<string>c[0], <string>c[1], <number>c[2])
}
onMounted(() => {
  emitter.on('reply', handleReply)
})

// 组件销毁时清理事件监听
onUnmounted(() => {
  emitter.off('reply', handleReply)
})

function replyToComment(commentUserName: string, commentText: string, commentId: number) {
  replyToCommentId.value = commentId
  oldComment.value = `回复:\n${commentUserName}`
  commentPlaceholder.value = `回复:\n评论id:${replyToCommentId.value}:\n${commentUserName}:\n\t${commentText}`
  const inputElement = document.getElementById('newCommentInput')
  if (inputElement) {
    inputElement.scrollIntoView({behavior: 'smooth', block: 'center'})
    inputElement.focus() // 设置焦点到输入框
  } else {
    console.warn('输入框未找到，无法滚动到该位置')
  }
}

function collectResource(rid: number) {
  axiosInstance.get(`${globalConst.baseUrl}user/collect/add/` + rid, {
    headers: {
      [globalConst.tokenName]: getUserToken()
    }
  }).then((res) => {
    const r = ResponseResult.fromApiResponse(res.data)
    if (r.isSuccess()) {
      alert('收藏成功!')
      isCollection.value = true
      addUserCollectionList(rid)
    } else {
      alert('收藏失败!原因为:' + r.msg)
    }
  })
}

async function clsCollectResource(id: number) {
  axiosInstance.get(`${globalConst.baseUrl}user/collect/del/` + id, {
    headers: {
      [globalConst.tokenName]: getUserToken()
    }
  }).then((res) => {
    const r = ResponseResult.fromApiResponse(res.data)
    if (r.isSuccess()) {
      alert('取消收藏成功!')
      isCollection.value = true
      delUserCollection(id)
    } else {
      alert('取消收藏失败!原因为:' + r.msg)
    }
  })
}
</script>
<style scoped>
/* 资源详情容器 */
.resource-detail-container {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding: 2rem;
}

/* 详情卡片 */
.resource-detail-card {
  background: rgba(42, 42, 42, 0.45);
  backdrop-filter: blur(5%);
  border-radius: 16px;
  padding: 2rem;
  width: 85%;
  max-width: 1100px;
  box-shadow: 0 8px 30px rgba(255, 42, 109, 0.1);
  border: 1px solid rgba(255, 42, 109, 0.2);
  animation: fadeIn 0.8s ease-out;
  color: var(--text-primary);
}

/* 标题部分 */
.resourceTitle {
  font-size: 1.8em;
  font-weight: 700;
  margin-bottom: 0.8rem;
  background: linear-gradient(135deg, var(--primary-red), var(--primary-purple));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 0 2px 8px rgba(255, 42, 109, 0.3);
  text-align: center;
}

/* 作者与类型 */
.resourceManufacturer,
.resourceType {
  text-align: center;
  color: var(--text-secondary);
  font-size: 1em;
  margin-bottom: 0.6rem;
}

/* 标签部分保持一致 */
.resourceTagContainer {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  justify-content: center;
  margin-bottom: 1rem;
}

.resourceTag {
  display: inline-block;
  padding: 0.3em 0.7em;
  border-radius: 20px;
  background: var(--secondary-gray);
  color: var(--text-primary);
  font-size: 0.8em;
  font-weight: 500;
}

.resourceTag:hover {
  background: linear-gradient(135deg, var(--primary-red), var(--primary-purple));
  box-shadow: 0 0 10px rgba(255, 42, 109, 0.3);
}

/* 预览图 */
.resourcePreviewContainer ul {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  padding: 0;
  list-style: none;
}

.resourcePreviewItem img {
  width: 260px;
  height: auto;
  border-radius: 12px;
  margin: 10px;
  box-shadow: 0 4px 16px rgba(255, 42, 109, 0.2);
  transition: all 0.3s ease;
}

.resourcePreviewItem img:hover {
  transform: scale(1.03);
  box-shadow: var(--shadow-glow);
}

/* 简介区 */
.resourceIntroductionContainer {
  background: rgba(0, 0, 0, 0.25);
  border-radius: 12px;
  padding: 1rem;
  color: var(--text-primary);
  margin-top: 1.2rem;
}

/* 评论区整体 */
.resourceCommentSection {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 12px;
  padding: 1rem;
  margin-top: 1.5rem;
}

.resourceCommentTitle {
  font-size: 1.2em;
  color: var(--primary-red);
  margin-bottom: 1rem;
  text-align: center;
}

/* 评论输入 */
.resourceCommentTextarea {
  width: 100%;
  background: var(--bg-secondary);
  border: 1px solid rgba(255, 42, 109, 0.3);
  border-radius: 10px;
  padding: 0.8em;
  color: var(--text-primary);
  resize: none;
}

/* 通用按钮（所有按钮统一卡片内样式） */
.resourceBtn {
  background: linear-gradient(135deg, var(--primary-red), var(--primary-purple));
  border-radius: 12px;
  padding: 0.5em 1.2em;
  font-weight: 600;
  color: var(--text-primary);
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  margin-top: 0.5rem;
}

.resourceBtn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s ease;
}

.resourceBtn:hover::before {
  left: 100%;
}

.resourceBtn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-glow);
}

/* 无资源提示 */
.resourceNoDataContainer {
  text-align: center;
  padding: 3rem;
}

.resourceNoDataHint {
  font-size: 1.2em;
  color: var(--text-secondary);
}

</style>
